<template>
  <div>
    <h1>{{id? '编辑':'新增'}}文章</h1>
    <el-form
      label-width="120px"
      @submit.native.prevent="save"
      :model="model"
      :rules="articleRules"
      ref="articleRef"
    >
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" multiple>
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="详情">
        <vue-editor v-model="model.body" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor"; // 富文本编辑器
export default {
  props: {
    id: {}
  },
  components: {
    VueEditor
  },
  data() {
    return {
      model: {
        title: "",
        body: ""
      },
      categories: [],
      articleRules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }]
      }
    };
  },
  methods: {
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      const formData = new FormData();
      formData.append("file", file);
      const res = await this.$http.post("upload", formData);
      Editor.insertEmbed(cursorLocation, "image", res.data.url); // 在光标位置插入
      resetUploader();
    },
    save() {
      this.$refs.articleRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("必填项不能为空");
        }
        let res;
        if (this.id) {
          res = await this.$http.put(`/rest/articles/${this.id}`, this.model);
        } else {
          res = await this.$http.post("/rest/articles", this.model);
        }
        this.$router.push("/articles/list"); // 创建完成之后跳转到列表
        this.$message({
          type: "success",
          message: "保存成功"
        });
      });
    },
    async fetch() {
      const res = await this.$http.get(`/rest/articles/${this.id}`); // 根据ID获取分类名称
      this.model = res.data;
    },
    async fetchCategories() {
      const res = await this.$http.get(`/rest/categories`); // 根据ID获取分类名称
      this.categories = res.data;
    }
  },
  created() {
    this.fetchCategories();
    this.id && this.fetch();
  }
};
</script>

<style>
</style>